using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using UnityEngine;

namespace BlockOS
{
    public class EventBus
    {
        private readonly Queue<GameEvent> eventQueue;
        private Dictionary<int, Action<GameEvent>> eventHandlers;

        public EventBus()
        {
            eventQueue = new();
            eventHandlers = new();
        }

        public void AddEvent(GameEvent gameEvent)
        {
            eventQueue.Enqueue(gameEvent);
        }

        public void AddEventHandler(int eventId, Action<GameEvent> handler)
        {
            if (eventHandlers.ContainsKey(eventId))
            {
                eventHandlers[eventId] += handler;
            }
            else
            {
                eventHandlers.Add(eventId, handler);
            }
        }

        public void SetEventHandler(int eventId, Action<GameEvent> handler)
        {
            eventHandlers[eventId] = handler;
        }

        public void RemoveEventHandler(int eventId, Action<GameEvent> handler)
        {
            if (eventHandlers.ContainsKey(eventId))
            {
                eventHandlers[eventId] -= handler;
            }
        }

        public void RemoveAllEventHanlder(int eventId)
        {
            eventHandlers[eventId] = null;
        }

        public void ProcessEvents(int maxEventCount)
        {
            while (eventQueue.Count > 0)
            {
                var e = eventQueue.Dequeue();
                if (eventHandlers.TryGetValue(e.id, out var handler))
                {
                    handler(e);
                }
                if (--maxEventCount <= 0) { break; }
            }
        }

        public void ProcessEvents()
        {
            while (eventQueue.Count > 0)
            {
                var e = eventQueue.Dequeue();
                if (eventHandlers.TryGetValue(e.id, out var handler))
                {
                    handler?.Invoke(e);
                }
            }
        }
    }
}
